package gokyesil.game2d.actors;

import gokyesil.game2d.renderer.Assets;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;

public class MapBlock extends Button 
{
	public Body body;
	protected final float scale = 0.05f;
	public MapBlock(ButtonStyle style, float x, float y, float width, float height, World physWorld)
	{
		super(style);
		this.setPosition(x, y);
		this.setWidth(width);
		this.setHeight(height);
		this.setBody(x, y, physWorld);
		
	}
    public void setBody(float x, float y, World physWorld)
    {
		BodyDef bodyDef = new BodyDef();
		if(((TextureRegionDrawable)this.getStyle().up).getRegion().getTexture() == Assets.brickList[0])
			bodyDef.type = BodyType.DynamicBody;
		else
			bodyDef.type = BodyType.StaticBody;
		bodyDef.position.set(scale*(x+this.getWidth()/2), scale*(y+this.getHeight()/2));
	    this.body = physWorld.createBody(bodyDef);
	    
	    PolygonShape dynamicBox = new PolygonShape();
	    dynamicBox.setAsBox(scale*this.getWidth()/2.0f, scale*this.getHeight()/2.0f);
	    
	    FixtureDef fixtureDef = new FixtureDef();
	    fixtureDef.shape = dynamicBox;
	    fixtureDef.density = 0.0f; 
	    fixtureDef.friction = 0.1f;
	    fixtureDef.restitution = 0.3f;
	    body.createFixture(fixtureDef);
    }
    public Body getBody()
    {
    	return this.body;
    }
	public void act (float delta)
	{
		super.act(delta);
    	Vector2 position = this.body.getPosition();
    	position.scl(1/scale).sub(this.getWidth()/2, this.getHeight()/2);
    	float angle = (float)(this.body.getAngle()*(180/Math.PI));
    	this.setPosition(position.x,position.y);
    	this.setRotation(angle);
	} 
	protected void drawBackground (Batch batch, float parentAlpha, float x, float y) 
	{
		if (this.getBackground() == null) return;
		Color color = getColor();
		batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
		batch.draw(((TextureRegionDrawable)this.getBackground()).getRegion(),getX(), getY(), getWidth()/2, getHeight()/2, getWidth(), getHeight(), 1, 1, getRotation());
	}
	public MapBlock clone(World newPhysWorld)
	{
		return new MapBlock(this.getStyle(),this.getX(),this.getY(),this.getWidth(), this.getHeight(),newPhysWorld);
	}
}
